from app01.Baseview import BasedAPIView
from app01.models import Port, NetDevice, Port_Log
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from datetime import datetime, timezone


class LogsAPI(BasedAPIView):
    def get_page_all(self, request):
        device_name = request.GET.get('name', '').strip()
        names_str = request.GET.get('names', '')
        port_names = names_str.split(',') if names_str else []
        # log_time = request.GET.getlist('log_time[]', None)
        log_time_str = request.GET.get('log_time', None)

        if not device_name and not port_names:
            return super().error(msg='请提供设备名称和端口名称作为搜索条件')

        port_ids = Port.objects.filter(name__in=port_names).values_list('id', flat=True)
        query = Q(port__device__name__icontains=device_name)
        if port_ids:
            query &= Q(port__id__in=port_ids)

        # if len(log_time) == 2:
        if log_time_str:
            # try:
            #     start = log_time[0]
            #     start_date = datetime.strptime(start[:19], "%Y-%m-%d %H:%M:%S")
            #     # 解析日期
            #     end = log_time[1]
            #     end_date = datetime.strptime(end[:19], "%Y-%m-%d %H:%M:%S")
            #     query &= Q(log_time__range=(start_date, end_date))
            # except ValueError as e:
            #     return super().error(msg=f"Error parsing date: {e}")
            start_time_str, end_time_str = log_time_str.split(',', 1)
            try:
                start_date = datetime.strptime(start_time_str.strip()[:19], "%Y-%m-%d %H:%M:%S")
                end_date = datetime.strptime(end_time_str.strip()[:19], "%Y-%m-%d %H:%M:%S")
                query &= Q(log_time__range=(start_date, end_date))
            except ValueError as e:
                return super().error(msg=f"Error parsing date: {e}")

        pageIndex = int(request.GET.get('pageIndex', 1))
        pageSize = int(request.GET.get('pageSize', 10))

        port_logs = Port_Log.objects.filter(query).select_related('port', 'port__device').order_by('-log_time')
        paginator = Paginator(port_logs, pageSize)
        page_data = paginator.page(pageIndex)

        resl = []
        for item in page_data:
            data_dic = {
                "id": item.id,
                "dev_info": {
                    "name": item.port.device.name,
                },
                "port_info": {
                    "name": item.port.name,
                },
                'traffic_in': round(int(item.traffic_in) / 1000000, 2),
                'traffic_out': round(int(item.traffic_out) / 1000000, 2),
                'log_time': item.log_time.strftime("%Y-%m-%d %H:%M:%S")
            }
            resl.append(data_dic)
        return super().success(data={
            'pageIndex': pageIndex,
            'pageSize': pageSize,
            'total': paginator.count,
            'data': resl
        })